//
//  TweetService.swift
//  Twitter
//
//  Created by Hoa.wang on 2022/4/7.
//

import ParseSwift

struct TweetService {
    
    func uploadTweet(caption: String, completion: @escaping (Tweet?) -> Void) {
        guard let uid = User.current?.objectId else {
            return
        }
        
        var tweet = Tweet()
        tweet.uid = uid
        tweet.caption = caption
        tweet.save { results in
            switch results {
            case .success(let tweet):
                completion(tweet)
            case .failure(let error):
                print("DEBUG: Failed to upload tweet with error: \(error)")
                completion(nil)
                
            }
        }
       
        var message = Message()
        message.uid = uid
        message.content = caption
        message.save { results in
            
        }
        
    }
    
    func fetchTweets(completion: @escaping ([Tweet]) -> Void) {
        
        Tweet.query().order([.descending("timeStamp")]).find { results in
            switch results {
            case .success(let tweets):
                completion(tweets)
            case .failure(let error):
                print("DEBUG: Failed to upload tweet with error: \(error)")
                completion([])
            }
        }
    }
    
    func fetchTweets(forUid uid: String, completion: @escaping ([Tweet]) -> Void) {
        Tweet.query("uid" == uid).find { results in
            switch results {
            case .success(let tweets):
                completion(tweets)
            case .failure(let error):
                print("DEBUG: Failed to upload tweet with error: \(error)")
                completion([])
            }
        }
    }
    
    
}
// MARK: - Likes
extension TweetService {
    
    func likeTweet(_ tweet: Tweet) async {
        
    }
    
    func unlikeTweet(_ tweet: Tweet) async {
       
    }
    
    func checkIfUserLikedTweet(_ tweet: Tweet) async -> Bool {
        
        false
    }
    
    func fetchLikedTweets(forUid uid: String, completion: @escaping ([Tweet]) -> Void) {
       
    }
    
}
